/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pranavpandey.ohos.dynamic.toasts.sample;

import ohos.agp.components.AttrHelper;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * 图片工具类
 *
 * @since 2021-07-13
 */
public class ImageTool {
    private ImageTool() {
    }

    /**
     * 通过图片ID返回PixelMap
     *
     * @param context 上下文
     * @param resourceId 图片的资源ID
     * @param width 图片宽度
     * @param height 图片高度
     * @return PixelMap
     */
    public static Optional<PixelMap> getPixelMap(Context context, int resourceId, int width, int height) {
        InputStream inputStream = null;
        ImageSource imageSource = null;
        ImageSource.DecodingOptions decodingOptions = null;
        try {
            // 创建图像数据源ImageSource对象
            inputStream = context.getResourceManager().getResource(resourceId);
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/png";
            imageSource = ImageSource.create(inputStream, srcOpts);

            // 设置图片参数
            decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(AttrHelper.vp2px(width, context),
                AttrHelper.vp2px(height, context));
        } catch (IOException | NotExistException   e) {
            e.getMessage();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.getMessage();
                }
            }
        }
        return imageSource == null ? Optional.empty() : Optional.ofNullable(imageSource.createPixelmap(decodingOptions));
    }
}
